<template>    
    <el-dialog
      style="top: -100px"
      :title="title"
      :visible.sync="visible"
      width="700px"
      :before-close="handleClose"
      class="announcement-edit-dialog"
    >
      <el-form :model="form" :rules="rules" ref="form" label-width="100px" label-position="right">
        <el-form-item label="公告标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入公告标题"></el-input>
        </el-form-item>
        
        <el-form-item label="公告状态" prop="status">
            <el-radio-group v-model="form.status">
                <el-radio :disabled="isPublishTime()" :label="0">待发布</el-radio>
                <el-radio :disabled="isPublishTime()" :label="1">已发布</el-radio>
            </el-radio-group>
        </el-form-item>
        
        <el-form-item label="公告内容" prop="content" ref="mdEditor" class="editor-form-item">
            <mavon-editor v-model="form.content" :toolbars="toolbars"/>
        </el-form-item>
        
        <el-form-item label="发布时间" prop="publishTime">
            <div class="block"> 
                <el-date-picker
                  v-model="form.publishTime"
                  type="date"
                  :disabled="disablePublishTime"
                  placeholder="选择日期">
                </el-date-picker>
            </div>
        </el-form-item>

        <!-- <mavon-editor v-model="form.content" :toolbars="{}" :editable="false" :subfield="false" defaultOpen="preview" :navigation="false"/> -->
      
        
        <el-form-item label="发布范围" prop="receivers">
            <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
            <div style="margin: 15px 0;"></div>
            <el-checkbox-group v-model="form.receivers" @change="handleReceiversChange">
              <el-checkbox v-for="city in cities" :label="city.label" :key="city.value" :disabled="isPublishTime() && checkedCities.includes(city.label)">{{city.label}}</el-checkbox>
            </el-checkbox-group>        
        </el-form-item>
      </el-form>
      
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="submitForm('form')">确 定</el-button>
      </span>
    </el-dialog>
  </template>
  
  <script>
import { mavonEditor } from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'
import { cloneDeep } from 'lodash';
import api from '@/api';


  export default {  
    components: {
        mavonEditor,
      },
    props: {
      visible: {
        type: Boolean,
        default: false
      },
      formData: {
        type: Object,
        default: () => ({})
      },
      title:{
        type: String,
        default: '新增公告'
      }
    },
    data() {
      return {
        buildNames: [],
        checkAll: false,
        cities: [],
        checkedCities:[],
        isIndeterminate: false,
        disablePublishTime: false,
        flack: false,
        form: {
          title: '',
          status: 0,
          content: '',
          publishTime: null,
          receivers: []
        },
        updateStatus:{
          initialStatus: 0,
        },
        rules: {
          title: [
            { required: true, message: '请输入公告标题', trigger: 'blur' }
          ],
          content: [
            { required: true, message: '请输入公告内容', trigger: 'blur' }
          ],
          publishTime: [
            { 
              type: 'date', 
              required: this.disablePublishTime,
              message: '请选择发布日期', 
              trigger: 'change' 
            },
            { 
              validator: this.validatePublishTime, 
              trigger: 'change' 
            }
          ],
          receivers: [
            { type: 'array', required: true, message: '请至少选择一个接收范围', trigger: 'change' }
          ]
        },
        toolbars: {
            bold: true, // 粗体
            italic: true, // 斜体
            header: true, // 标题
            underline: true, // 下划线
            strikethrough: true, // 中划线
            mark: true, // 标记
            quote: true, // 引用
            ol: true, // 有序列表
            ul: true, // 无序列表
            code: true, // code
            table: true, // 表格
            fullscreen: true, // 全屏编辑
            htmlcode: true, // 展示html源码
            help: true, // 帮助
            /* 1.3.5 */
            undo: true, // 上一步
            redo: true, // 下一步
            trash: true, // 清空
            /* 2.1.8 */
            alignleft: true, // 左对齐
            aligncenter: true, // 居中
            alignright: true, // 右对齐
            /* 2.2.1 */
            subfield: true, // 单双栏模式
            preview: true, // 预览
        }
      }
    },
    methods: {
      validatePublishTime(rule, value, callback) {
        if (!value) {
          return callback(); // 如果值为空，跳过验证（已被 required 校验）
        }

        const selectedDate = new Date(value).setHours(0, 0, 0, 0); // 去掉时间部分，仅保留日期
        const today = new Date().setHours(0, 0, 0, 0);

        if (!this.disablePublishTime && !this.isPublishTime() && selectedDate <= today) {
          callback(new Error('发布日期必须大于当前日期'));
        } else {
          callback();
        }
      },
      submitForm(form) {
        this.$refs[form].validate((valid) => {
          if (valid) {
            //获取发布范围的IDs
            let receiverIdList = [];
            this.form.receivers.forEach(receiverLabel =>{
                const matchedCity = this.cities.find(city => city.label === receiverLabel);
                if(matchedCity){
                  receiverIdList.push(matchedCity.value);
                }
            })
            //数据处理
            this.form.receiverIds = receiverIdList.join(",");

            if((this.form.id && this.form.status === 1) || (!this.form.id && this.form.status ===1 )){
                // 获取当前日期
                this.form.publishTime = new Date();
            }

            if (this.form.publishTime instanceof Date) {
                this.form.publishTime = this.formatDate(this.form.publishTime);
            }else{
              const dateObj = new Date(this.form.publishTime);
              this.form.publishTime = this.formatDate(dateObj);
            }

            // 提交表单数据
            api.noticeAdd(this.form).then(res =>{
                if(res.type === 'error'){
                    this.$message.error(res.message)
                }else if(res.data.code === 200){
                  this.$message({
                    message: '操作成功',
                    type: 'success'
                  });
                  this.handleClose();
                  location.reload();
                }else{
                  this.$message.error(res.data.message)
                }
            })


            this.handleClose();
          } else {
            this.$message.error('请完善表单信息');
            return false;
          }
        });
      },

      //设置日期格式
      formatDate(date) {
          const year = date.getFullYear();
          const month = String(date.getMonth() + 1).padStart(2, '0');
          const day = String(date.getDate()).padStart(2, '0');
          return `${year}-${month}-${day}`;
      },
      
      handleClose() {
        // 手动清空表单
        this.form = {
              title: '',
              status: 0,
              content: '',
              publishTime: null,
              receivers: []
        };
        // 重置表单验证状态
        this.$refs['form'].resetFields();
        this.$emit('update:visible', false);
        this.$emit('update:title', '新增公告');
        this.$emit('updateFormData', {});
        this.checkAll = false
        this.isIndeterminate = false
      },
      isPublishTime(){
        if(this.title === '编辑公告' && this.formData.status !== 0){
            return true
        }
        return false
      },
      getReceivers(){
        //获取楼宇信息
        api.buildListAll().then(res =>{
            if(res.type === 'error'){
                this.$message.error(res.message)
            }else if(res.data.code === 200){
              const tableData = res.data.data.buildInfos;
              // 去重后的 buildingName 列表
              this.buildNames = tableData.map(item => ({value: item.id,label: item.buildingName+'-'+item.unit}))
              this.cities = this.buildNames;
            }else{
              this.$message.error(res.data.message)
            }
        })
      },
      handleCheckAllChange(val) {
        this.form.receivers = val ? this.cities.map(city => city.label) : ( this.isPublishTime() ? this.checkedCities : []);
        if(this.isPublishTime() && !val){
          this.isIndeterminate = true;
          return
        }
        this.isIndeterminate = false;
      },
      handleReceiversChange(value) { 
        let checkedCount = value.length;
        this.checkAll = (checkedCount === this.cities.length) && this.cities.length !== 0;
        this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length;
      }
    },
    computed: {
        // 将 Markdown 文本编译为 HTML
        compiledMarkdown() {
            return marked.parse(this.markdownText);
        },
    },
    watch: {
        // 监听 formData 的变化
        formData: {
            handler(newVal) {
                if (newVal && Object.keys(newVal).length > 0) {
                    // 深拷贝 formData 并赋值给 ruleForm
                    this.form = cloneDeep(newVal);
                    this.checkedCities = cloneDeep(this.form.receivers);
                    this.handleReceiversChange(this.form.receivers)
                }
            },
            immediate: true, // 立即执行一次
            deep: true, // 深度监听
        },
        // 监听 form.status 的变化
        'form.status': {
            handler(newStatus) {
                if (newStatus === 1 && this.title === '新增公告') {
                    // 当是新增公告且状态为已发布时，禁用发布时间
                    this.disablePublishTime = true;
                    this.$set(this.rules.publishTime[0], 'required', false);
                    this.form.publishTime = null
                }else if(newStatus === 1 && this.title === '编辑公告') {
                  this.disablePublishTime = true;
                  this.$set(this.rules.publishTime[0], 'required', false);
                } else{
                    // 否则启用发布时间
                    this.disablePublishTime = false;
                    this.$set(this.rules.publishTime[0], 'required', true);
                }
            },
            immediate: true
        },
        'form.publishTime': {
          handler(newVal) {
            if (newVal && typeof newVal === 'string') {
              this.form.publishTime = new Date(newVal);
            }
          },
          immediate: true
        }
    },
    created(){
        this.getReceivers();
    }
  }
  </script>
  
  <style scoped>

  .announcement-edit-dialog >>> .el-dialog__body {
    padding: 20px 30px;
  }
  
  .editor-wrapper {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    overflow: hidden;
  }
  
  .editor-toolbar {
    border-bottom: 1px solid #dcdfe6;
    background-color: #f5f7fa;
  }
  
  .editor-content {
    min-height: 300px;
    max-height: 500px;
    overflow-y: auto;
  }
  
  .editor-form-item >>> .el-form-item__content {
    line-height: normal;
  }
  
  .line {
    line-height: 36px;
    color: #909399;
  }
  </style>